﻿using System.Data.OracleClient;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Configuration;

namespace BSC_SERVICES.Code
{
    public class Login
    {
        #region khai bao bien
        string _connectstring = ConfigurationManager.AppSettings["ConnectString"].ToString();
        OracleDataAdapter _da = new OracleDataAdapter();
        OracleCommand _cmd = new OracleCommand();
        OracleConnection _con = new OracleConnection();
        DataTable _table = new DataTable("tlprofiles");
        Code.CL_Ultility _cl = new CL_Ultility();
        #endregion

        #region ham connect
        private void OpenConnect()
        {
            _con.ConnectionString = _connectstring;
            _con.Open();
        }

        private void CloseConnect()
        {
            _con.Close();
        }
        #endregion

        // check login
        public bool CheckLogin(string _username, string _password)
        {
            _cmd = _con.CreateCommand();
            _cmd.CommandType = CommandType.Text;
            _cmd.CommandText = "SELECT * FROM tlprofiles WHERE tlname like UPPER (:username) and pin like :password AND Active='Y'";
            _cmd.Parameters.Add("username", OracleType.VarChar).Value = _username;
            _cmd.Parameters.Add("password", OracleType.VarChar).Value = this.md5(_password);
            _cmd.Connection = _con;
            OpenConnect();
            _da = new OracleDataAdapter(_cmd);
            _da.Fill(_table);
            CloseConnect();
            if (_table.Rows.Count == 0)
            {
                return false;
            }
            return true;
        }

        private  byte[] encryptData(string data)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider md5Hasher = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] hashedBytes;
            System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
            hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(data));
            return hashedBytes;
        }

        private  string md5(string data)
        {
            return BitConverter.ToString(encryptData(data)).Replace("-", "").ToLower();
        }

        public DataTable Return_Datatable(string _sql)
        {
            try
            {
                OpenConnect();
                _da = new OracleDataAdapter(_sql, _con);
                DataTable result = new DataTable("noname");
                _da.Fill(result);
                CloseConnect();
                return result;
            }
            catch (Exception ex)
            {
                _cl.UPDATE_LOG_FILE("ERR", null, "Return_Datatable", "Return_Datatable", ex.Message);
                return null;
            }
        }
    }
}